<template>
  <div class="app-container">
    <div class="top-title">
      <!-- {{stepName}} -->
              <div>{{stepName}}</div>
              <div class="btn-search top-title" @click="showDialog()">
                <span>筛选</span>
                <img class="down-icon" src="../../assets/images/arrow down.png" alt="">
              </div>
            </div>
    <div class="chart" ref="chart" />

    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <!-- <el-form-item label="地区" prop="courseArea">
            <el-cascader
              clearable
              filterable
              placeholder="省/市/区"
              :options="addRessList"
              :props="cityProps"
              v-model="queryParams.courseArea"
              popper-class="pc-sel-area-cascader"
              @change="areaCodeChange"
            />
          </el-form-item> -->
          <!-- <el-form-item label="授课学校" prop="courseDept">
            <el-select v-model="queryParams.courseDept" placeholder="请选择学校" clearable @change="change">
              <el-option v-for="item in tenantOptions" :key="item.tenantId" :label="item.companyName" :value="item.tenantId"> </el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item label="学年" prop="courseYear">
            <el-select v-model="queryParams.courseYear" placeholder="请选择学年" clearable @change="change">
              <el-option key="2024-2025" label="2024-2025" value="2024-2025"> </el-option>
              <!-- <el-option v-for="item in tenantOptions" :key="item.tenantId" :label="item.companyName" :value="item.tenantId"> </el-option> -->
            </el-select>
          </el-form-item>
          <el-form-item label="学段" prop="coursePeriod">
            <el-select v-model="queryParams.coursePeriod" placeholder="请选择学段" clearable @change="coursePeriodChange">
              <el-option v-for="dict in courseList" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"> </el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="学科" prop="courseSubject">
            <el-select v-model="queryParams.courseSubject" placeholder="请选择学科" clearable @change="change">
              <el-option v-for="dict in subjectOptions" :key="dict.id" :label="dict.subjectName" :value="dict.id"></el-option>
            </el-select>
          </el-form-item> -->
          <!-- <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item> -->
        </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog> 

  </div>
</template>

<script setup name="BarChart" lang="ts">
import { chartByPeriod, getRoom, delRoom, addRoom, updateRoom } from '@/api/core/home';
import { getDicts } from '@/api/system/dict/data';

// import { ChartSchoolVO, ChartSchoolQuery, RoomForm } from '@/api/core/home/types';
import * as echarts from 'echarts';
const { proxy } = getCurrentInstance();
// sys_period
const { sys_notice_type,  sys_grade } = toRefs<any>(proxy?.useDict('sys_notice_type', 'sys_grade'));
//学科
import { getSubjectNameById } from '@/utils/index';
import { useSubjectList } from '@/composables/useSubjectList';
const { subjectOptions, fetchSubjectList } = useSubjectList();

interface Props {
    schoolId:{
        type: String,
        default:''
    },
}
const props = defineProps<Props>()

// const dialog = reactive<DialogOption>({
//   visible: false,
//   title: ''
// });
//学校改租户数据
import { useTenantlList } from '@/composables/useSchoolList';
const { tenantOptions, fetchTenantlList,tenantDisabled} = useTenantlList();
import cityData from '@/assets/json/pca-code.json';
const addRessList = ref(cityData);
const cityProps = reactive({
  emitPath: false,
  value: 'code', //指定选项的值为addresslist对象的code属性
  label: 'name', //指定选项标签为addresslist对象的name属性
  children: 'children' //指定选项的子选项为addresslist对象的children属性
});

const dialog = reactive<DialogOption>({
  visible: false,
  title: '筛选'
});
const queryParams = ref({
    // courseArea: undefined, //地区
    courseDept: undefined,//学校
    courseYear: undefined, //学年
    coursePeriod: undefined,//学段
    // courseSubject: undefined,//学科
    params: {}
});
const stepName = ref<string>()
let courseList = [];

// const list = toRaw((sys_period._object)['sys_period'])
// if(sys_period.value && sys_period.value.length > 0){
//   stepName.value = sys_period.value[0].label;
//   // toRaw(proxy?.useDict( 'sys_period'))['sys_period'];
//   queryParams.value.coursePeriod = list[0].value;
// }
// // console.log('=============',toRaw(sys_period['_object']['sys_period']));
// console.log('=============',(sys_period._object)['sys_period'],list,toRaw(proxy?.useDict( 'sys_period'))['sys_period']);

watch(() => props.schoolId, (newVal, oldVal) => {
    // 如果 courseArea 发生变化，
    console.log('阶段监听学校id===',newVal)
    // queryParams.courseDept.value = newVal;
    if (newVal !== oldVal && newVal) {
        //根据学校id获取学科学段 先不获取，固定的
    }
    },{
        immediate:true,
        deep:true},
);

const showDialog = async () => {
  dialog.visible = true;
}
/** 搜索按钮操作 */
const submitForm = async () => {
  dialog.visible = false;
  await getList();
};
/**取消 */
const cancel = async () => {
  dialog.visible = false;
  // queryParams.courseArea = undefined
};
const areaCodeChange = (e)=>{
  console.log('地区选择',e)
  //根据地区重新获取学校数据
  fetchTenantlList(e);
  //重置学校数据
  queryParams.courseDept = undefined;
}

 const coursePeriodChange = (e) => {
   console.log('选择学段',e,courseList);
   courseList.forEach(ele =>{
     if(ele.dictValue == e){
      stepName.value = ele.dictLabel;
     }
   })
 }

const getList = async () => {
  // loading.value = true;
  const res = await chartByPeriod(queryParams.value);
  const list = res.data;
  const subjectList = [];
  const chartData = [];
  //处理返回键值对数据
  Object.keys(list).forEach(key => {
    console.log(key + ': ' + list[key]);
    const name = key;
    subjectList.push(name);
    chartData.push(list[key].replace(new RegExp("%", 'g'), ''))
    
  });
  console.log('高中阶段',res.data,subjectList,chartData);

  let chart = echarts.init(proxy.$refs.chart);
  chart.setOption({
    xAxis: {
      type: 'category',
      data: subjectList
      //  ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    },
    yAxis: {
      type: 'value',
      max: 100
    },
    series: [
      {
        data: chartData,
        // [120, 200, 150, 80, 70, 110, 130],
        type: 'bar',
        showBackground: true,
        backgroundStyle: {
          color: 'rgba(180, 180, 180, 0.2)'
        }
      }
    ]
  });
}
const getCoursePeriodList = async ()=>{
  const res = await getDicts('sys_period')
  courseList = res.data;
  stepName.value = res.data?res.data[0].dictLabel:"";
  queryParams.value.coursePeriod = res.data?res.data[0].dictValue:"";
  console.log('学段列表',res.data,courseList);

  // await getDicts('sys_period').then((resp) => {
          // courseList.value = resp.data
          // .map(
          //   (p) => ({ label: p.dictLabel, value: p.dictValue, elTagType: p.listClass, elTagClass: p.cssClass })
          // );
  // });
}
onMounted(() => {
  
  getList();
  getCoursePeriodList();
});
</script>
<style lang="scss" scoped>
.app-container {
  width: 100%;
  .chart {
    width: 100%;
    height: 300px;
  }
}
.top-title{
  font-size: 20px;
  color: #141414;
  line-height: 28px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .btn-search{
    font-size: 14px;
    color: #999999;
    padding: 0 10px;
    width: 100px;
    border-radius: 4px;
    border: 1px solid #DCDFE6;
    .down-icon{
      width: 12px;
      height: 6px;
    }
  }
}
</style>
